package com.android.antelopeapp.view.CNArticle;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;

import com.android.antelopeapp.R;
import com.android.antelopeapp.activity.ActivityManager;
import com.android.antelopeapp.activity.BaseActivity;
import com.android.antelopeapp.bean.CNContent;
import com.android.antelopeapp.constant.ApiConfig;
import com.android.antelopeapp.constant.MsgConfig;
import com.android.antelopeapp.network.GsonRequest;
import com.android.antelopeapp.network.NetworkManager;
import com.android.antelopeapp.utils.NetworkUtils;
import com.android.antelopeapp.view.MyPagingListView;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.lyhw.model.Article;
import com.lyhw.model.Attach;
import com.lyhw.model.beanwraper.WraperFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by phk on 15-4-13.
 */
public class CNArticleListView extends MyPagingListView {
    public static String TAG = "CNArticleListView";
    private String mArticleTypeId;
    private int viewItemResId = R.layout.view_ra_content_item;
    private long afterTime=0;
    public CNArticleListView(Context context) {
        super(context);
    }

    public CNArticleListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CNArticleListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void init(BaseActivity bacty,String articleType){
        this.mArticleTypeId = articleType;
        init(bacty);
    }

    public void init(BaseActivity bacty,int viewItemResId){
        this.viewItemResId = viewItemResId;
        init(bacty);
    }

    @Override
    protected void initAdapter() {
        CNCAdapter adapter = new CNCAdapter(bacty) {

            @Override
            public void OnClickImgBg(int position) {
                Log.v("ReArticleListFragment", "on click img bg pos=" + position);
                ActivityManager.startReArticleDetailActivity(bacty, getSpeItem(position).get_article().getId());
            }

            @Override
            public void OnClickImgBtn(int position) {
                //点击左上角按钮查看该类目下更多信息
                Log.v("CNHomeFragment", "click imgBtnMore at position "+position);
                CNContent con = getSpeItem(position);
                if(con.get_article()!=null) {
                    ActivityManager.startReArticleListActivity(bacty, con.get_article().getTypeid(),0);
                }else{
                    //todo 容错处理 如果没有相应的文章信息，如何处理
                    bacty.sendToastMsg(MsgConfig.GET_MORE_ARTICLE_FAILED);
                }
            }
        };
        adapter.setViewResource(viewItemResId);
        setAdapter(adapter);
    }

    /**
     * 更新listview
     * */
    protected void updateListView(){
        if(!NetworkUtils.isNetworkConnected(bacty.getApplicationContext())){
            bacty.sendToastMsg(MsgConfig.NETWORK_FAILED);
            stopLoadingBar();
        }else{
            String url = ApiConfig.REQUEST_ARTICLE_LIST;
            if(mArticleTypeId != null){
                url+=mArticleTypeId+"/";
            }
            url+="?"+ApiConfig.RA_START_POS+"="+mStartPos+"&sort=crtime,desc";
            GsonRequest<WraperFactory.ArticleListWraper> grequest = new GsonRequest<WraperFactory.ArticleListWraper>(Request.Method.GET,
                    url,
                    WraperFactory.ArticleListWraper.class,
                    null,
                    new Response.Listener<WraperFactory.ArticleListWraper>() {
                        @Override
                        public void onResponse(WraperFactory.ArticleListWraper response) {
                            List<CNContent> clist = new ArrayList<>();
                            List<Article> rlist = response.getData().getContent();
                            if(rlist != null&&rlist.size()!=0) {
                                afterTime=rlist.get(0).getCrtime();
                                for (int i = 0; i < rlist.size(); i++) {
                                    Article article = rlist.get(i);
                                    if(rlist.get(i).getAttach()==null){
                                        rlist.get(i).setAttach(new Attach());
                                    }
                                    clist.add(new CNContent(rlist.get(i)));
                                }
                            }else{
                                //todo 容错处理 当json数据获取失败
                                Log.d(TAG,"rlist is empty.");
                                //clist = CNHomeFragment.getTestData();
                                bacty.sendToastMsg(MsgConfig.GET_ARTICLE_FAILED);
                                stopLoadingBar();
                            }
                            addPage();
                            addItemsToList(!response.getData().isLast(),clist);
                        }
                    },new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //todo 容错处理
                    Log.w(TAG,"onErrorResponse "+error.getMessage());
//                addItemsToList(false,CNHomeFragment.getTestData());
                    bacty.sendToastMsg(MsgConfig.GET_ARTICLE_FAILED);
                    stopLoadingBar();
                }
            });

            NetworkManager.getInstance(bacty).getRequestQueue().add(grequest);
        }

    }

    public void refreshListView(){
        if(getFooterViewsCount()==0){
            addLoadingBar();
        }
        if(!NetworkUtils.isNetworkConnected(bacty.getApplicationContext())){
            bacty.sendToastMsg(MsgConfig.NETWORK_FAILED);
            stopLoadingBar();
        }else{
            String url = ApiConfig.REQUEST_ARTICLE_LIST;
            if(mArticleTypeId != null){
                url+=mArticleTypeId+"/";
            }
            long resuertTime=afterTime+1001;
            url+="?"+ApiConfig.AFTER_TIME+"="+resuertTime+"&sort=crtime,desc";
            Log.v(TAG,url);
            GsonRequest<WraperFactory.ArticleListWraper> grequest = new GsonRequest<WraperFactory.ArticleListWraper>(Request.Method.GET,
                    url,
                    WraperFactory.ArticleListWraper.class,
                    null,
                    new Response.Listener<WraperFactory.ArticleListWraper>() {
                        @Override
                        public void onResponse(WraperFactory.ArticleListWraper response) {
                            List<CNContent> addList=new ArrayList<>();
                            List<Article> rlist = response.getData().getContent();
                            if(rlist != null&&rlist.size()!=0) {
                                afterTime=rlist.get(0).getCrtime();
                                Log.d(TAG,"addList is not empty.");
                                for (int i = 0; i < rlist.size(); i++) {
                                    Article article = rlist.get(i);
                                    if(rlist.get(i).getAttach()==null){
                                        rlist.get(i).setAttach(new Attach());
                                    }
                                    addList.add(new CNContent(rlist.get(i)));
                                }
                                bacty.sendToastMsg(MsgConfig.REQUEST_SUCCESS);
                                addItemsToHeadList(!response.getData().isLast(),addList);
                            }else{
                                //todo 容错处理 当json数据获取失败
                                Log.d(TAG,"addList is empty.");
                                //clist = CNHomeFragment.getTestData();
                                bacty.sendToastMsg(MsgConfig.HAS_NO_MORE);
                                stopLoadingBar();
                            }
                            //  addPage();
                        }
                    },new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //todo 容错处理
                    Log.w(TAG,"onErrorResponse "+error.getMessage());
//                addItemsToList(false,CNHomeFragment.getTestData());
                    bacty.sendToastMsg(MsgConfig.GET_ARTICLE_FAILED);
                    stopLoadingBar();
                }
            });
            NetworkManager.getInstance(bacty).getRequestQueue().add(grequest);
        }
    }
}
